package com.easyfun.healthmagicbox.sync;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.comm.BaseCommTask;
import com.easyfun.healthmagicbox.comm.BaseRedoTask;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.util.SharedPreferencesUtil;

public class BasicCommCallback implements CommCallback{
	
	String resultValue = "";
	public ServerResponseCode result = ServerResponseCode.WAITING;
	
	public Handler mHandler;
	
	public BasicCommCallback() {
		mHandler = null;
	}
	public BasicCommCallback(Handler handler) {
		mHandler = handler;
	}
	@Override
	public void setCommResult(BaseCommTask task, String id2, ServerResponseCode result) {
		resultValue = id2;
		this.result = result;
		
		if (result == ServerResponseCode.FAILED)
		{
			if (task instanceof BaseRedoTask)
			{
				BaseRedoTask task2 = (BaseRedoTask)task;
				
				Integer taskID = task2.getRedoTaskID();
				//Never redo
				if (taskID == 0)
				{
					taskID = SharedPreferencesUtil.getInstance(task2.getContext()).getRedoTaskID();
					task2.setRedoTaskID(taskID);
					task2.setRedoTaskTimes(task2.getRedoTaskTimes()+1);
				}else
				{
					task2.setRedoTaskTimes(task2.getRedoTaskTimes()+1);
				}
				
				String serializedTask = "";
				try
				{
					serializedTask = task2.serialize();
				}catch(IllegalArgumentException e)
				{
					//this redo task can't be serialized.
					return;
				}
				
				SyncManager syncMgr = SyncManager.getInstance();
				if (syncMgr!=null)
					syncMgr.registerFailedTask(serializedTask);
				SharedPreferencesUtil.getInstance(task2.getContext()).storeRedoTask(taskID, serializedTask);
			}
			
		}else if ((result == ServerResponseCode.SUCCESS)||(result == ServerResponseCode.NOMORE))
		{
			if (task instanceof BaseRedoTask)
			{
				BaseRedoTask task2 = (BaseRedoTask)task;
				Integer redoID = task2.getRedoTaskID();
				if (redoID!=null)
				{
					SharedPreferencesUtil.getInstance(task2.getContext()).removeRedoTask(redoID);
				}
			}
			
		
		}
		
		if(mHandler != null) {
			Message msg = mHandler.obtainMessage();  
			Log.d("Ping", "msg.what = " + msg.what + "\n");
            msg.what = result.toInteger();  
            msg.sendToTarget();  
		}
		
	}

	@Override
	public ServerResponseCode getCommResult(Class<?> c, String id) {
		id = resultValue;
		return result;
	}

	@Override
	public void initialStatus() {
		result = ServerResponseCode.WAITING;
		
	}
	
	public String getResultValue()
	{
		return resultValue;
	}
}
